import { Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm'; 
import { AutomationConditionEntity } from '../../entity/condition';
import { AutomationTaskEntity } from '../../entity/task';
import { AutomationPipelineEntity } from '../../entity/pipeline';

/**
 * 自动化流水线
 */
@Provide()
export class AutomationPipelineService extends BaseService {
  @InjectEntityModel(AutomationPipelineEntity)
  automationPipelineEntity: Repository<AutomationPipelineEntity>;

  @InjectEntityModel(AutomationConditionEntity)
  automationConditionEntity: Repository<AutomationConditionEntity>;

  @InjectEntityModel(AutomationTaskEntity)
  automationTaskEntity: Repository<AutomationTaskEntity>;

  /**
   * 新增流水线
   * @param params
   */
  async addPipeline(params: any) {
    const { conditions, tasks, ...pipeline } = params;
    const pipelineResult = await this.automationPipelineEntity.save(pipeline);

    if (conditions && conditions.length > 0) {
      conditions.forEach(condition => condition.pipelineId = pipelineResult.id);
      /* 触发条件 */
      await this.automationConditionEntity.save(conditions);
    }

    if (tasks && tasks.length > 0) {
      tasks.forEach(task => task.pipelineId = pipelineResult.id);
      /* 执行 */
      await this.automationTaskEntity.save(tasks);
    }

    return pipelineResult;
  }

  /**
   * 更新流水线
   * @param params
   */
  async updatePipeline(params: any) {
    const { conditions, tasks, id, ...pipeline } = params;

    await this.automationPipelineEntity.update(id, pipeline);

    if (conditions) {
      await this.automationConditionEntity.delete({ pipelineId: id });
      if (conditions.length > 0) {
        conditions.forEach(condition => condition.pipelineId = id);
        await this.automationConditionEntity.save(conditions);
      }
    }

    if (tasks) {
      await this.automationTaskEntity.delete({ pipelineId: id });
      if (tasks.length > 0) {
        tasks.forEach(task => task.pipelineId = id);
        await this.automationTaskEntity.save(tasks);
      }
    }

    return '更新成功';
  }

  /**
   * 删除流水线
   * @param ids
   */
  async deletePipeline(ids: number[]) {
    await this.automationPipelineEntity.delete(ids);
    await this.automationConditionEntity.delete({ pipelineId: ids as any });
    await this.automationTaskEntity.delete({ pipelineId: ids as any });
    return '删除成功';
  }

  /**
   * 获取流水线详情
   * @param id
   */
  async pipelineDetail(id: number) {
    const pipeline = await this.automationPipelineEntity.findOneBy({ id });
    if (!pipeline) {
      return null;
    }
    const conditions = await this.automationConditionEntity.findBy({ pipelineId: id });
    const tasks = await this.automationTaskEntity.findBy({ pipelineId: id });
    return { ...pipeline, conditions, tasks };
  }
}